import { DeleteParams, PaginationParam, PaginationResult } from "./models";
import req from "./req";
import { RequestMethodEnum } from "./req/httpEnum";

export interface CURDApiOptions {
  getPageUrl?: string;
  getDataUrl?: string;
  cudUrl?: string;
  getDataMethod?: RequestMethodEnum;
  getPageMethod?: RequestMethodEnum;
}
export function getPage<T = any>(url: string, params: PaginationParam<T>) {
  return req.get<PaginationResult<T>>(
    {
      params,
      url,
    },
    {
      useGlobalLoading: false,
    }
  ) as Promise<PaginationResult<T> | null>;
}
export default class CURD<T, K> {
  options: CURDApiOptions;
  constructor(options: CURDApiOptions) {
    options = Object.assign(
      {
        getDataMethod: RequestMethodEnum.GET,
        getPageMethod: RequestMethodEnum.GET,
      },
      options
    );
    this.options = options;
  }
  getData(params?: K) {
    if (!this.options.getDataUrl) {
      return Promise.reject("getDataUrl is not defined");
    }
    const method = (this.options.getDataMethod as string).toLowerCase();
    return req[method]<T[]>(
      {
        data: params,
        url: this.options.getDataUrl,
      },
      {
        useGlobalLoading: false,
      }
    );
  }
  getPage(params: PaginationParam<K>) {
    if (!this.options.getPageUrl) {
      return Promise.reject("getPageUrl is not defined");
    }
    if (params.model) {
      Object.assign(params, params.model);
      delete params.model;
    }
    const method = (this.options.getPageMethod as string).toLowerCase();
    return req[method]<PaginationResult<T>>(
      {
        [method === RequestMethodEnum.GET.toLocaleLowerCase() ? "params" : "data"]: params,
        url: this.options.getPageUrl,
      },
      {
        useGlobalLoading: false,
      }
    );
  }
  create(params: T) {
    return req.post<T>({
      data: params,
      url: this.options.cudUrl,
    });
  }
  update(params: T) {
    return req.put<T>({
      data: params,
      url: this.options.cudUrl,
    });
  }
  delete(params: DeleteParams) {
    return req.delete<boolean>({
      params,
      url: this.options.cudUrl,
    });
  }
}
